$(function () {

    var layer = layui.layer
    //获取轮播图列表
    getSwiperList()
    function getSwiperList() {
        $.ajax({
            type: 'get',
            url: '/admin/swipers',
            success: function (res) {
                if (res.status != 0) {
                    return layer.msg(res.message)
                }
                //渲染
                var str = template("tpl-swiper", res)
                $('tbody').html(str)
            }
        })

    }

    //修改轮播图状态
    $('tbody').on('click', '.layui-badge', function () {
        //获取id
        var id = $(this).attr('data-id')
        var status = $(this).attr('data-status')
        // console.log(status);
        // status = (status == 2) ? 1 : 2
        // console.log(status);
        $.ajax({
            type: 'put',
            url: '/admin/swipers/' + id,
            data: {
                status
            },
            success: function (res) {
                if (res.status != 0) {
                    return layer.msg(res.message)
                }
                //重新渲染
                getSwiperList()
            }
        })
    })

    //批量上传轮播图
    $('.layui-btn').on('click', function () {
        $('#myfile').click()
    })

    $('#myfile').on('change', function () {
        // console.log(this.files);

        var arr = Array.from(this.files)
        // console.log(arr);
        var fd = new FormData();
        for (var i = 0; i < arr.length; i++) {
            fd.append('swipers', arr[i])
        }
        if (arr.length >= 20) {
            return layer.msg('一次性不能上传超过20张的图片')
        }
        $.ajax({
            type: 'post',
            url: '/admin/swipers',
            contentType: false,
            processData: false,
            data: fd,
            success: function (res) {
                if (res.status != 0) {
                    return layer.msg(res.message)
                }
                layer.msg(res.message, function () {
                    getSwiperList()
                })

            }
        })
    })

    //删除轮播图
    $('tbody').on('click', '.delete', function () {
        var id = $(this).attr('data-id')
        //弹出询问框
        layer.confirm('确定要删除吗?', { icon: 3, title: '提示' }, function (index) {

            $.ajax({
                type: 'delete',
                url: '/admin/swipers/' + id,
                success: function (res) {
                    if (res.status != 0) {
                        return layer.msg(res.mmessage)
                    }
                    //重新渲染
                    getSwiperList()
                }
            })
            layer.close(index);
        });
    })







})